package com.sdap2.service.impl;

import com.sdap2.common.exception.BusinessException;
import com.sdap2.common.utils.WebClientUtil;
import com.sdap2.dto.DeviceDataResponse;
import com.sdap2.entity.Greenhouse;
import com.sdap2.service.DeviceDataService;
import com.sdap2.service.GreenhouseService;
import com.sdap2.dao.GreenhouseDAO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class DeviceDataServiceImpl implements DeviceDataService {
    
    private final WebClientUtil webClientUtil;
    private final GreenhouseService greenhouseService;
    private final GreenhouseDAO greenhouseDAO;
    
    @Override
    @Transactional
    public List<DeviceDataResponse> getDeviceData(Long greenhouseId, List<String> deviceIds, String token) {
        // 获取大棚信息
        Greenhouse greenhouse = greenhouseService.getById(greenhouseId, token);
        
        try {
            List<DeviceDataResponse> data = webClientUtil.getDeviceData(greenhouse, deviceIds);
            // 如果token被更新了，保存到数据库
            greenhouseDAO.save(greenhouse);
            return data;
        } catch (Exception e) {
            throw new BusinessException("获取设备数据失败: " + e.getMessage());
        }
    }
} 